package servlet;

import servlet.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userList")
public class UserListServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        int page = 1; // 默认显示第一页
        int recordsPerPage = 5; // 每页显示 5 条记录

        // 从请求参数中获取当前页码
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }

        List<User> userList = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/FinalTest", "root", "123456");

            // 计算分页的起始位置
            int start = (page - 1) * recordsPerPage;

            // 查询分页数据
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM user LIMIT ?, ?");
            ps.setInt(1, start);
            ps.setInt(2, recordsPerPage);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setEmail(rs.getString("email"));
                user.setGender(rs.getString("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setLans(rs.getString("lans"));
                userList.add(user);
            }

            // 查询总记录数
            Statement stmt = conn.createStatement();
            ResultSet rsTotal = stmt.executeQuery("SELECT COUNT(*) AS total FROM user");
            rsTotal.next();
            int totalRecords = rsTotal.getInt("total");
            int totalPages = (int) Math.ceil(totalRecords * 1.0 / recordsPerPage);

            // 将数据传递给 JSP 页面
            request.setAttribute("userList", userList);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("currentPage", page);
            request.getRequestDispatcher("userList.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}